package com.kj.xuyuan;

import android.app.NotificationChannel;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kj.xuyuan.base.ActivityCollector;
import com.kj.xuyuan.base.BaseActivity;
import com.kj.xuyuan.base.BaseModel;
import com.kj.xuyuan.base.Constants;
import com.kj.xuyuan.chat.ChatActivity;
import com.kj.xuyuan.http.JsonCallback;
import com.kj.xuyuan.http.OkGoUtil;
import com.kj.xuyuan.http.UrlConstants;
import com.kj.xuyuan.model.EventBusBean;
import com.kj.xuyuan.model.SignBean;
import com.kj.xuyuan.model.UserInfoBean;
import com.kj.xuyuan.pop.SignPopWindow;
import com.kj.xuyuan.util.JSONUtils;
import com.kj.xuyuan.util.LogUtils;
import com.kj.xuyuan.util.SPUtils;
import com.kj.xuyuan.util.ToastUtil;
import com.kj.xuyuan.widget.NoScrollViewPager;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.IMCenter;
import io.rong.imkit.RongIM;
import io.rong.imkit.config.RongConfigCenter;
import io.rong.imkit.notification.DefaultInterceptor;
import io.rong.imkit.utils.RouteUtils;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;

public class MainActivity extends BaseActivity {

    @BindView(R.id.vp_main)
    NoScrollViewPager vpMain;
    @BindView(R.id.iv_home)
    ImageView ivHome;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.ll_home)
    LinearLayout llHome;
    @BindView(R.id.iv_matchmaker)
    ImageView ivMatchmaker;
    @BindView(R.id.tv_matchmaker)
    TextView tvMatchmaker;
    @BindView(R.id.ll_matchmaker)
    LinearLayout llMatchmaker;
    @BindView(R.id.iv_msg)
    ImageView ivMsg;
    @BindView(R.id.tv_msg)
    TextView tvMsg;
    @BindView(R.id.ll_msg)
    LinearLayout llMsg;
    @BindView(R.id.iv_mine)
    ImageView ivMine;
    @BindView(R.id.tv_mine)
    TextView tvMine;
    @BindView(R.id.ll_mine)
    LinearLayout llMine;

    private MainPageController pageController;
    private int mCurrentPage = 0;
    private boolean isExit;

    @Override
    protected void init(Bundle savedInstanceState) {

    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        pageController = new MainPageController(MainActivity.this, vpMain);
        getSignInfo(1);
        EventBus.getDefault().register(this);

        initRongIm();
    }

    private void initRongIm() {
        RongIM.init(getApplication(), "0vnjpoad0lwkz",false);

        LogUtils.e(TAG,"Constants.RONG_TOKEN ="+SPUtils.getStringData(context, Constants.RONG_TOKEN, ""));
        RongIM.connect(SPUtils.getStringData(context, Constants.RONG_TOKEN, ""), new RongIMClient.ConnectCallback() {
            @Override
            public void onSuccess(String s) {
                LogUtils.e(TAG,"onSuccess ="+s);
            }

            @Override
            public void onError(RongIMClient.ConnectionErrorCode connectionErrorCode) {
                LogUtils.e(TAG,"onError ="+connectionErrorCode.getValue());
            }

            @Override
            public void onDatabaseOpened(RongIMClient.DatabaseOpenStatus databaseOpenStatus) {
                LogUtils.e(TAG,"onDatabaseOpened =");
            }
        });

        RongIM.setConnectionStatusListener(new RongIMClient.ConnectionStatusListener() {
            @Override
            public void onChanged(RongIMClient.ConnectionStatusListener.ConnectionStatus connectionStatus) {

            }
        });

        IMCenter.getInstance().addOnReceiveMessageListener(new RongIMClient.OnReceiveMessageWrapperListener() {
            @Override
            public boolean onReceived(Message message, int i, boolean b, boolean b1) {
                LogUtils.e(TAG,message.toString());
                return false;
            }
        });

        RongConfigCenter.notificationConfig().setInterceptor(new DefaultInterceptor() {
            @Override
            public boolean isNotificationIntercepted(Message message) {
                return true;
            }

            @Override
            public PendingIntent onPendingIntent(PendingIntent pendingIntent, Intent intent) {
                return super.onPendingIntent(pendingIntent, intent);
            }

            @Override
            public boolean isHighPriorityMessage(Message message) {
                return false;
            }

            @Override
            public NotificationChannel onRegisterChannel(NotificationChannel defaultChannel) {
                return super.onRegisterChannel(defaultChannel);
            }
        });

        RouteUtils.registerActivity(RouteUtils.RongActivityType.ConversationActivity, ChatActivity.class);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeData(EventBusBean eventBus){
        LogUtils.e("TAG","changeData"+eventBus.getCode());
        if (eventBus.getCode()==1001){//HomeFragment点击签到按钮，弹出签到弹窗
            getSignInfo(2);
        }
    }

    private void getSignInfo(int type) {
        OkGoUtil.postRequest(getContext(), UrlConstants.SIGN_INFO, null, new JsonCallback<BaseModel<SignBean>>() {
            @Override
            public void onSuccess(Response<BaseModel<SignBean>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        if(response.body().getData().getIs_sign() == 0){
                            popSignWindow(response.body().getData());
                        }else if(type == 2){
                            popSignWindow(response.body().getData());
                        }
                    }
                    ToastUtil.showToast(getContext(),response.body().getMsg());
                }
            }

            @Override
            public void onError(Response<BaseModel<SignBean>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
            }
        });
    }

    private void popSignWindow(SignBean signBean) {
        SignPopWindow popWindow = new SignPopWindow(context,signBean);
        popWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER,0,0);
        popWindow.setAnimationStyle(R.style.popwindow_center_anim_style);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getTitleBarType() {
        return -1;
    }

    @OnClick({R.id.ll_home, R.id.ll_matchmaker, R.id.ll_msg, R.id.ll_mine})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_home:
                if(mCurrentPage != 0){
                    mCurrentPage = 0;
                    changePage();
                }
                break;
            case R.id.ll_matchmaker:
                if(mCurrentPage != 1){
                    mCurrentPage = 1;
                    changePage();
                }
                break;
            case R.id.ll_msg:
                if(mCurrentPage != 2){
                    mCurrentPage = 2;
                    changePage();
                }
                break;
            case R.id.ll_mine:
                if(mCurrentPage != 3){
                    mCurrentPage = 3;
                    changePage();
                }
                break;
        }
    }

    private void changePage() {
        // TODO: 2021/8/30 首页icon没有
        pageController.ChangePage(mCurrentPage);
        switch (mCurrentPage){
            case 0:
                tvHome.setTextColor(getResources().getColor(R.color.color_ff4d91));
                tvMatchmaker.setTextColor(getResources().getColor(R.color.color_b5b5b5));
                tvMsg.setTextColor(getResources().getColor(R.color.color_b5b5b5));
                tvMine.setTextColor(getResources().getColor(R.color.color_b5b5b5));

                ivMatchmaker.setImageResource(R.mipmap.icon_matchmaker_gray);
                ivMsg.setImageResource(R.mipmap.icon_msg_gray);
                ivMine.setImageResource(R.mipmap.icon_mine_gray);

                break;
            case 1:
                tvHome.setTextColor(getResources().getColor(R.color.color_b5b5b5));
                tvMatchmaker.setTextColor(getResources().getColor(R.color.color_ff4d91));
                tvMsg.setTextColor(getResources().getColor(R.color.color_b5b5b5));
                tvMine.setTextColor(getResources().getColor(R.color.color_b5b5b5));

                ivMatchmaker.setImageResource(R.mipmap.icon_matchmaker_pink);
                ivMsg.setImageResource(R.mipmap.icon_msg_gray);
                ivMine.setImageResource(R.mipmap.icon_mine_gray);
                break;
            case 2:
                tvHome.setTextColor(getResources().getColor(R.color.color_b5b5b5));
                tvMatchmaker.setTextColor(getResources().getColor(R.color.color_b5b5b5));
                tvMsg.setTextColor(getResources().getColor(R.color.color_ff4d91));
                tvMine.setTextColor(getResources().getColor(R.color.color_b5b5b5));

                ivMatchmaker.setImageResource(R.mipmap.icon_matchmaker_gray);
                ivMsg.setImageResource(R.mipmap.icon_msg_pink);
                ivMine.setImageResource(R.mipmap.icon_mine_gray);
                break;
            case 3:
                tvHome.setTextColor(getResources().getColor(R.color.color_b5b5b5));
                tvMatchmaker.setTextColor(getResources().getColor(R.color.color_b5b5b5));
                tvMsg.setTextColor(getResources().getColor(R.color.color_b5b5b5));
                tvMine.setTextColor(getResources().getColor(R.color.color_ff4d91));

                ivMatchmaker.setImageResource(R.mipmap.icon_matchmaker_gray);
                ivMsg.setImageResource(R.mipmap.icon_msg_gray);
                ivMine.setImageResource(R.mipmap.icon_mine_pink);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitByDoubleClick();
        }
        return false;
    }

    //双击返回退出
    private void exitByDoubleClick() {
        Timer tExit = null;
        if (!isExit) {
            isExit = true;
            Toast.makeText(this, "再返回一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;//取消退出
                }
            }, 2000);// 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            finish();
            System.exit(0);
        }
    }
}